package com.inspector.app.ui.flight

import android.annotation.SuppressLint
import android.content.Context
import android.os.BatteryManager
import android.view.View
import android.widget.FrameLayout
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.google.gson.Gson
import com.google.gson.JsonParser
import com.inspector.app.R
import com.inspector.app.databinding.FragmentFlightBinding
import com.inspector.app.di.location.LocationInstance
import com.inspector.app.di.util.UI
import com.inspector.app.di.util.fromJson
import com.inspector.app.di.vo.LocationPosition
import com.inspector.app.ui.flight.statusBar.FlightStatusBar
import com.inspector.app.ui.flight.statusBar.FlightStatusBarAdapter
import com.inspector.app.ui.flight.statusBar.FlightStatusBarPopup
import com.inspector.app.ui.flight.statusBar.FlightStatusBarPopup.OnItemClickListener
import com.inspector.app.ui.flight.statusBar.FlightStatusBarUtils
import com.inspector.app.ui.widget.decoration.GridItemDecoration
import com.inspector.app.util.ConstantUtil
import com.inspector.app.util.LogUtil
import com.inspector.app.util.SharedPreferencesUtils
import kotlinx.coroutines.delay
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.launch
import org.oscim.backend.canvas.Color
import java.lang.ref.WeakReference
import java.util.concurrent.CopyOnWriteArrayList
import kotlin.random.Random


/**
 * 飞行状态栏相关
 */
class StatusBarLifecycleObserver : DefaultLifecycleObserver {

    private val TAG: String = StatusBarLifecycleObserver::class.java.simpleName
    private var intervalTime = 0L

    private val _allItems = CopyOnWriteArrayList<FlightStatusBar>() //[标题栏对应集合]
    val allItems get() = _allItems

    private val positionItems = CopyOnWriteArrayList<LocationPosition>() //[定位点集合]

    private var statusBarAdapter: FlightStatusBarAdapter? = null
    private var batteryManager: BatteryManager? = null
    @SuppressLint("CheckResult")
    fun setupView(fragment: FlightFragment, viewBinding: FragmentFlightBinding) {
        LogUtil.e(TAG, "飞行状态栏 setupView")
        batteryManager = viewBinding.root.context.getSystemService(Context.BATTERY_SERVICE) as BatteryManager
        statusBarAdapter = FlightStatusBarAdapter()

        viewBinding.statusBarRV.apply {
            adapter = statusBarAdapter
            addItemDecoration(
                GridItemDecoration.Builder(this.context)
                    .setColor(Color.parseColor("#585858"))
                    .setHorizontalSpan(R.dimen.dp_1)
                    .setVerticalSpan(R.dimen.dp_1)
                    .setShowLastLine(false)
                    .build()
            )
        }

        //[点击事件]
        statusBarAdapter?.setOnItemClickListener { _, view, position ->
            showPopup(view) { popupItem, _, _ ->
                allItems[position] = popupItem
                dismissPopup()

                SharedPreferencesUtils.put(ConstantUtil.USERID, ConstantUtil.FLIGHT_STATUS_BAR_KEY, Gson().toJson(allItems.map { it.name }.toMutableList()))
            }
        }

        //[指南针被遮挡]
        fragment.efbMap.compassImageView?.apply {
            if (layoutParams is FrameLayout.LayoutParams) {
                val marginSpace = UI.dipToPx(12f)
                val height = UI.dipToPx(114f) + UI.getStatusBarHeight(fragment.requireActivity()) + marginSpace
                (layoutParams as FrameLayout.LayoutParams).setMargins(marginSpace, height, 0, 0)
            }
        }
    }

    private var statusBarPopupRef: WeakReference<FlightStatusBarPopup>? = null
    private fun showPopup(v: View, listener: OnItemClickListener) {
        dismissPopup()
        val flightStatusBarPopup = FlightStatusBarPopup(v.context, FlightStatusBar.entries, v.tag, listener)
        flightStatusBarPopup.showAtLocation(v)
        statusBarPopupRef = WeakReference(flightStatusBarPopup)
    }
    private fun dismissPopup() {
        val statusBarPopup = statusBarPopupRef?.get()
        if (statusBarPopup?.isShowing == true) {
            statusBarPopup.dismiss()
        }
        statusBarPopupRef?.clear()
        statusBarPopupRef = null
    }


    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
        LogUtil.e(TAG, "飞行状态栏 onCreate")
        val flightStatusBars = FlightStatusBar.entries.toMutableList()
        val items = flightStatusBars.subList(0, 8).toMutableList() //[默认前八个]

        val statusBarJSON = SharedPreferencesUtils.getString(ConstantUtil.USERID, ConstantUtil.FLIGHT_STATUS_BAR_KEY)
        if (statusBarJSON?.isNotEmpty() == true) {
            val nameItems = fromJson<MutableList<String>>(JsonParser.parseString(statusBarJSON))
            if (nameItems?.isNotEmpty() == true) {
                items.clear()
                nameItems.forEachIndexed { _, name ->
                    var statusBar = flightStatusBars.firstOrNull { it.name == name }
                    if (statusBar == null) { //[找不到, 随机展示一个]
                        statusBar = flightStatusBars[Random.nextInt(flightStatusBars.size)]
                    }
                    items.add(statusBar)
                }
            }
        }

        allItems.clear()
        allItems.addAll(items)
        SharedPreferencesUtils.put(ConstantUtil.USERID, ConstantUtil.FLIGHT_STATUS_BAR_KEY, Gson().toJson(allItems.map { it.name }.toMutableList()))

        val viewModel = (owner as FlightFragment).viewModel
        owner.lifecycleScope.launch {
            owner.lifecycle.repeatOnLifecycle(Lifecycle.State.RESUMED) {
                intervalTime = System.currentTimeMillis()
                while (true) {
                    refreshStatusBar(viewModel)
                    intervalTime = System.currentTimeMillis()
                    delay(1000)
                    ensureActive()
                }
            }
        }

        /*var i = 0
        var intervalTime = 0L
        owner.lifecycleScope.launch {
            owner.repeatOnLifecycle(Lifecycle.State.CREATED) {
                intervalTime = System.currentTimeMillis()
                while (true) {
                    delay(1000)
                    LogUtil.e(TAG, "MapLifecycleObserver i:$i intervalTime:${System.currentTimeMillis() - intervalTime}")
                    intervalTime = System.currentTimeMillis()
                    i += 1
                    ensureActive()
                }
            }
        }*/
    }


    //[刷新状态栏]
    private fun refreshStatusBar(viewModel: FlightViewModel) {
        val lastKnownLocation = LocationInstance.getInstance().lastKnownLocation
//        LogUtil.e(TAG, "飞行状态栏 刷新时间间隔:${System.currentTimeMillis() - intervalTime} lastKnownLocation:$lastKnownLocation")

        allItems.forEach { flightStatusBar ->
            when (flightStatusBar) {
                FlightStatusBar.BJSJ -> {
                    FlightStatusBarUtils.formatBJTime(flightStatusBar)
                }
                FlightStatusBar.HX -> {
                    FlightStatusBarUtils.formatHX(flightStatusBar, lastKnownLocation)
                }
                FlightStatusBar.HBGD -> {
                    FlightStatusBarUtils.formatAltitude(flightStatusBar, lastKnownLocation)
                }
                FlightStatusBar.SD -> {
                    FlightStatusBarUtils.formatSpeed(flightStatusBar, lastKnownLocation)
                }
                FlightStatusBar.DQJWD -> {
                    FlightStatusBarUtils.formatDQJWD(flightStatusBar, lastKnownLocation)
                }
                FlightStatusBar.CC -> {
                    FlightStatusBarUtils.formatMagneticDif(flightStatusBar, lastKnownLocation)
                }
                FlightStatusBar.YFJL -> {
                    // TODO: 已飞距离

                }
                FlightStatusBar.DL -> {
                    FlightStatusBarUtils.formatDL(flightStatusBar, batteryManager)
                }
                FlightStatusBar.UTC -> {
                    FlightStatusBarUtils.formatUTC(flightStatusBar)
                }
                FlightStatusBar.WXS -> {
                    FlightStatusBarUtils.formatWXS(flightStatusBar)
                }
                FlightStatusBar.JSQ -> {
                    // TODO: 计时器 1.viewModel.flightStatusBarTimer 2.repeatOnLifecycle(Lifecycle.State.CREATED) 两种思路

                }
                FlightStatusBar.CHX -> {
                    FlightStatusBarUtils.formatMagneticHeading(flightStatusBar, lastKnownLocation)
                }
                else -> {}
            }
        }

        //[刷新状态栏和弹窗]
        statusBarAdapter?.submitList(allItems)
        statusBarPopupRef?.get()?.updateAdapter()
    }

    override fun onDestroy(owner: LifecycleOwner) {
        super.onDestroy(owner)
        dismissPopup()
        statusBarAdapter = null
        batteryManager = null
        LogUtil.e(TAG, "飞行状态栏 onDestroy")
    }

    override fun onPause(owner: LifecycleOwner) {
        super.onPause(owner)
        LogUtil.e(TAG, "飞行状态栏 onPause")
    }

    override fun onStop(owner: LifecycleOwner) {
        super.onStop(owner)
        LogUtil.e(TAG, "飞行状态栏 onStop")
    }

    override fun onResume(owner: LifecycleOwner) {
        super.onResume(owner)
        LogUtil.e(TAG, "飞行状态栏 onResume")
    }


}